<template>
    <div class="home-container">
        <!-- 顶部导航栏 -->
        <div class="nav-bar">
            <div class="nav-content">
                <div class="nav-left">
                    <el-button type="text" @click="$router.push('/favorites')">
                        <el-icon><Star /></el-icon>
                        我的收藏
                    </el-button>
                </div>
                <!-- ... 其他导航内容 -->
            </div>
        </div>

        <!-- 顶部大图轮播 -->
        <div class="hero-section">
            <el-carousel :interval="4000" type="card" height="400px">
                <el-carousel-item v-for="banner in banners" :key="banner.id">
                    <div class="banner-item" :style="{ backgroundImage: `url(${banner.image})` }">
                        <div class="banner-content">
                            <h2>{{ banner.title }}</h2>
                            <p>{{ banner.description }}</p>
                            <el-button type="primary" size="large" @click="goToPromotion(banner)">
                                立即查看
                            </el-button>
                        </div>
                    </div>
                </el-carousel-item>
            </el-carousel>
        </div>

        <!-- 主要内容区 -->
        <div class="main-content">
            <!-- 分类快捷导航 -->
            <div class="category-shortcuts">
                <div class="shortcut-item" v-for="cat in categories" :key="cat.id" @click="handleCategorySelect(cat.id)">
                    <el-icon class="shortcut-icon"><component :is="cat.icon" /></el-icon>
                    <span>{{ cat.name }}</span>
                </div>
            </div>

            <!-- 热门活动区 -->
            <div class="promotions-section">
                <div class="section-header">
                    <h2>热门活动</h2>
                    <el-button type="text">查看更多 ></el-button>
                </div>
                <el-row :gutter="20">
                    <el-col :span="8" v-for="promo in promotions" :key="promo.id">
                        <div class="promo-card" @click="goToPromotion(promo)">
                            <div class="promo-image">
                                <img :src="promo.image" :alt="promo.title">
                                <div class="promo-tag" v-if="promo.tag">{{ promo.tag }}</div>
                            </div>
                            <div class="promo-content">
                                <h3>{{ promo.title }}</h3>
                                <p>{{ promo.description }}</p>
                            </div>
                        </div>
                    </el-col>
                </el-row>
            </div>

            <!-- 商品展示区 -->
            <div class="products-section">
                <div class="section-header">
                    <h2>{{ currentCategoryName }}</h2>
                    <div class="filters">
                        <el-radio-group v-model="sortBy" size="small">
                            <el-radio-button label="default">默认</el-radio-button>
                            <el-radio-button label="sales">销量优先</el-radio-button>
                            <el-radio-button label="price">价格优先</el-radio-button>
                        </el-radio-group>
                    </div>
                </div>

                <el-row :gutter="20">
                    <el-col :span="6" v-for="product in sortedProducts" :key="product.id">
                        <div class="product-card" @click="showProductDetail(product)">
                            <div class="product-image">
                                <img :src="product.image" :alt="product.name">
                                <div class="product-tags" v-if="product.tags">
                                    <el-tag 
                                        v-for="tag in product.tags" 
                                        :key="tag"
                                        size="small"
                                        :type="getTagType(tag)"
                                    >
                                        {{ tag }}
                                    </el-tag>
                                </div>
                                <div class="quick-actions">
                                    <el-button circle type="primary" @click.stop="addToCart(product)">
                                        <el-icon><ShoppingCart /></el-icon>
                                    </el-button>
                                    <el-button circle @click.stop="toggleFavorite(product)">
                                        <el-icon><Star /></el-icon>
                                    </el-button>
                                </div>
                            </div>
                            <div class="product-info">
                                <h3>{{ product.name }}</h3>
                                <div class="product-meta">
                                    <span class="brand">{{ product.brand }}</span>
                                    <span class="sales">月销 {{ product.sales || 0 }}</span>
                                </div>
                                <div class="product-price-row">
                                    <span class="price">¥{{ product.price.toFixed(2) }}</span>
                                    <span class="original-price" v-if="product.originalPrice">
                                        ¥{{ product.originalPrice.toFixed(2) }}
                                    </span>
                                </div>
                            </div>
                        </div>
                    </el-col>
                </el-row>

                <!-- 加载更多 -->
                <div class="load-more" v-if="hasMore">
                    <el-button type="primary" plain @click="loadMore" :loading="loading">
                        加载更多
                    </el-button>
                </div>
            </div>

            <!-- 推荐区域 -->
            <div class="recommendations-section" v-if="recommendations.length">
                <div class="section-header">
                    <h2>为你推荐</h2>
                </div>
                <el-row :gutter="20">
                    <el-col :span="4" v-for="item in recommendations" :key="item.id">
                        <div class="recommend-card">
                            <img :src="item.image" :alt="item.name">
                            <h4>{{ item.name }}</h4>
                            <p class="recommend-price">¥{{ item.price.toFixed(2) }}</p>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </div>

        <!-- 商品详情弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            title="商品详情"
            width="60%"
            :before-close="handleClose"
        >
            <div class="product-detail" v-if="selectedProduct">
                <div class="detail-gallery">
                    <el-image
                        :src="selectedProduct.image"
                        :preview-src-list="[selectedProduct.image]"
                    />
                </div>
                <div class="detail-info">
                    <h2>{{ selectedProduct.name }}</h2>
                    <div class="detail-tags">
                        <el-tag 
                            v-for="tag in selectedProduct.tags" 
                            :key="tag"
                            :type="getTagType(tag)"
                            size="small"
                        >
                            {{ tag }}
                        </el-tag>
                    </div>
                    <div class="detail-price">
                        <span class="current-price">¥{{ selectedProduct.price.toFixed(2) }}</span>
                        <span class="original-price" v-if="selectedProduct.originalPrice">
                            ¥{{ selectedProduct.originalPrice.toFixed(2) }}
                        </span>
                    </div>
                    <div class="detail-meta">
                        <span>品牌：{{ selectedProduct.brand }}</span>
                        <span>库存：{{ selectedProduct.stock }}</span>
                        <span>月销：{{ selectedProduct.sales || 0 }}</span>
                    </div>
                    <p class="detail-desc">{{ selectedProduct.description }}</p>
                    <div class="detail-actions">
                        <el-input-number v-model="purchaseQuantity" :min="1" :max="selectedProduct.stock" />
                        <el-button type="primary" @click="addToCartFromDialog">
                            加入购物车
                        </el-button>
                        <el-button type="warning" @click="buyNow">
                            立即购买
                        </el-button>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 购物车抽屉 -->
        <el-drawer
            v-model="cartDrawerVisible"
            title="购物车"
            direction="rtl"
            size="30%"
        >
            <cart-drawer-content />
        </el-drawer>
    </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'

export default {
  name: 'HomePageView',
  setup() {
    const store = useStore()
    const products = ref([])
    const cartItems = ref([])
    const categories = computed(() => store.state.products.categories)
    const currentCategory = ref('')
    const sortBy = ref('default')
    const dialogVisible = ref(false)
    const selectedProduct = ref(null)
    const purchaseQuantity = ref(1)
    const cartDrawerVisible = ref(false)

    const currentCategoryName = computed(() => {
        if (!currentCategory.value) return '全部零食'
        const category = categories.value.find(c => c.id === currentCategory.value)
        return category ? category.name : '全部零食'
    })

    const handleCategorySelect = async (categoryId) => {
        currentCategory.value = categoryId
        await store.dispatch('products/setCategory', categoryId)
        await loadProducts()
    }

    const loadProducts = async () => {
        try {
            const response = await store.dispatch('products/getProducts')
            products.value = response
        } catch (error) {
            ElMessage.error('获取商品列表失败')
        }
    }

    const addToCart = (product) => {
        const existingItem = cartItems.value.find(item => item.id === product.id)
        if (existingItem) {
            existingItem.quantity++
        } else {
            cartItems.value.push({
                ...product,
                quantity: 1
            })
        }
        saveCart()
        ElMessage.success('已添加到购物车')
    }

    const saveCart = () => {
        localStorage.setItem('cart', JSON.stringify(cartItems.value))
    }

    const loadCart = () => {
        const savedCart = localStorage.getItem('cart')
        if (savedCart) {
            cartItems.value = JSON.parse(savedCart)
        }
    }

    const showProductDetail = (product) => {
        selectedProduct.value = product
        dialogVisible.value = true
    }

    const handleClose = () => {
        dialogVisible.value = false
        selectedProduct.value = null
        purchaseQuantity.value = 1
    }

    const addToCartFromDialog = () => {
        if (selectedProduct.value) {
            const product = { ...selectedProduct.value }
            product.quantity = purchaseQuantity.value
            addToCart(product)
            dialogVisible.value = false
        }
    }

    const buyNow = () => {
        addToCartFromDialog()
        cartDrawerVisible.value = true
    }

    const toggleFavorite = (product) => {
        // 添加到收藏列表的逻辑
        ElMessage({
            message: `已将 ${product.name} 加入收藏`,
            type: 'success',
            duration: 2000
        })
    }

    const getTagType = (tag) => {
        const tagTypes = {
            '新品': 'success',
            '热销': 'danger',
            '促销': 'warning'
        }
        return tagTypes[tag] || 'info'
    }

    const banners = [
        {
            id: 1,
            title: '零食狂欢节',
            description: '全场满99减50',
            image: './333/图片/零食狂欢节.jpg',
            link: '/promotion/1'
        },
        {
            id: 2,
            title: '进口零食专场',
            description: '低至5折起',
            image: './333/图片/进口零食.jpg',
            link: '/promotion/2'
        },
        {
            id: 3,
            title: '休闲零食',
            description: '第二件半价',
            image: './333/图片/休闲零食.jpg',
            link: '/promotion/3'
        }
    ]

    const promotions = [
        {
            id: 1,
            title: '进口零食专场',
            description: '低至5折起',
            image: './333/图片/进口零食专区.jpg',
            tag: '限时'
        },
        {
            id: 2,
            title: '休闲零食专场',
            description: '第二件半价',
            image: './333/图片/休闲零食专区.jpg',
            tag: '热门'
        },
        {
            id: 3,
            title: '饮料专场',
            description: '满99减30',
            image: './333/图片/饮料专区.jpg',
            tag: '活动'
        }
    ]

    const recommendations = ref([
        {
            id: 1,
            name: '乐事薯片',
            price: 9.90,
            image: './333/图片/乐事薯片.jpg'
        },
        {
            id: 2,
            name: '可口可乐',
            price: 3.50,
            image: './333/图片/可口可乐.jpg'
        },
        {
            id: 3,
            name: '旺旺雪饼',
            price: 8.80,
            image: './333/图片/旺旺雪饼.jpg'
        },
        {
            id: 4,
            name: '费列罗巧克力',
            price: 58.90,
            image: './333/图片/费列罗.jpg'
        },
        {
            id: 5,
            name: '百事可乐',
            price: 3.50,
            image: './333/图片/百事可乐.jpg'
        },
        {
            id: 6,
            name: '康师傅方便面',
            price: 4.50,
            image: './333/图片/康师傅方便面.jpg'
        }
    ])

    const sortedProducts = computed(() => {
        let result = [...products.value]
        switch (sortBy.value) {
            case 'price':
                result.sort((a, b) => a.price - b.price)
                break
            case 'sales':
                result.sort((a, b) => (b.sales || 0) - (a.sales || 0))
                break
            default:
                // 默认排序，保持原顺序
                break
        }
        return result
    })

    const goToPromotion = (item) => {
        // 实际跳转到促销页面的逻辑
        console.log('跳转到促销页面:', item.link)
    }

    onMounted(async () => {
        await loadProducts()
        loadCart()
    })

    return {
        currentCategoryName,
        handleCategorySelect,
        loadProducts,
        addToCart,
        saveCart,
        loadCart,
        showProductDetail,
        handleClose,
        addToCartFromDialog,
        buyNow,
        toggleFavorite,
        getTagType,
        banners,
        promotions,
        recommendations,
        sortedProducts,
        goToPromotion
    }
  }
}
</script>

<style scoped>
.home-container {
    min-height: 100vh;
    background: #f5f7fa;
}

.hero-section {
    margin-bottom: 40px;
}

.banner-item {
    height: 100%;
    background-size: cover;
    background-position: center;
    border-radius: 8px;
    position: relative;
    overflow: hidden;
}

.banner-content {
    position: absolute;
    left: 50px;
    top: 50%;
    transform: translateY(-50%);
    color: white;
    text-shadow: 0 2px 4px rgba(0,0,0,0.5);
    background: rgba(0,0,0,0.3);
    padding: 20px;
    border-radius: 8px;
}

.banner-content h2 {
    font-size: 36px;
    margin: 0 0 20px;
}

.main-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}

.category-shortcuts {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
    gap: 20px;
    margin-bottom: 40px;
}

.shortcut-item {
    text-align: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.3s;
}

.shortcut-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.shortcut-icon {
    font-size: 30px;
    margin-bottom: 10px;
    color: #ff6b6b;
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    font-size: 24px;
    margin: 0;
    color: #333;
}

.promo-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    cursor: pointer;
    transition: all 0.3s;
}

.promo-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.promo-image {
    position: relative;
    height: 250px;
    overflow: hidden;
}

.promo-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    transition: transform 0.3s;
}

.promo-tag {
    position: absolute;
    top: 10px;
    right: 10px;
    background: #ff6b6b;
    color: white;
    padding: 4px 8px;
    border-radius: 4px;
}

.promo-content {
    padding: 15px;
}

.product-card {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 20px;
    cursor: pointer;
    transition: all 0.3s;
}

.product-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
}

.product-image {
    position: relative;
    height: 200px;
}

.product-image img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.product-tags {
    position: absolute;
    top: 10px;
    left: 10px;
    display: flex;
    gap: 5px;
}

.quick-actions {
    position: absolute;
    bottom: 10px;
    right: 10px;
    display: flex;
    gap: 10px;
    opacity: 0;
    transition: opacity 0.3s;
}

.product-card:hover .quick-actions {
    opacity: 1;
}

.product-info {
    padding: 15px;
}

.product-info h3 {
    margin: 0 0 10px;
    font-size: 16px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.product-meta {
    display: flex;
    justify-content: space-between;
    color: #999;
    font-size: 12px;
    margin-bottom: 10px;
}

.product-price-row {
    display: flex;
    align-items: baseline;
    gap: 10px;
}

.price {
    color: #ff6b6b;
    font-size: 20px;
    font-weight: bold;
}

.original-price {
    color: #999;
    text-decoration: line-through;
    font-size: 14px;
}

.load-more {
    text-align: center;
    margin: 40px 0;
}

.recommendations-section {
    margin-top: 60px;
    padding-top: 40px;
    border-top: 1px solid #eee;
}

.recommend-card {
    text-align: center;
    padding: 10px;
}

.recommend-card img {
    width: 100%;
    height: 180px;
    object-fit: cover;
    border-radius: 4px;
    transition: transform 0.3s;
}

.recommend-card:hover img {
    transform: scale(1.05);
}

.recommend-card h4 {
    margin: 10px 0 5px;
    font-size: 14px;
}

.recommend-price {
    color: #ff6b6b;
    margin: 0;
}

@media (max-width: 768px) {
    .category-shortcuts {
        grid-template-columns: repeat(4, 1fr);
    }

    .banner-content {
        left: 20px;
    }

    .banner-content h2 {
        font-size: 24px;
    }
}

/* 添加导航栏样式 */
.nav-bar {
    background: white;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    position: sticky;
    top: 0;
    z-index: 100;
}

.nav-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 10px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.nav-left {
    display: flex;
    gap: 20px;
    align-items: center;
}
</style>
